package com.sweet.logging.factory;

import com.sweet.logging.logger.SweetLogManager;
import com.sweet.logging.logger.SweetLogger;
import com.sweet.logging.logger.SweetLoggerAdapter;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Logger 工厂，有SLF4J API 调用，创建实际的Logger对象。
 *
 * @version 1.0     2017年09月08日  10点25分
 */
public class SweetLoggerFactory implements ILoggerFactory
{
    private ConcurrentMap<String, Logger> loggerMap; // Logger对象缓存

    public SweetLoggerFactory()
    {
        loggerMap = new ConcurrentHashMap<>();
    }

    public Logger getLogger(String name)
    {
        Logger slf4jLogger = loggerMap.get(name);
        if (slf4jLogger != null) {
            return slf4jLogger;
        } else
        {
            SweetLogger sweetLogger;
            if (name.equalsIgnoreCase(Logger.ROOT_LOGGER_NAME))
                sweetLogger = SweetLogManager.getRootLogger();
            else
                sweetLogger = SweetLogManager.getLogger(name);
            Logger newInstance = new SweetLoggerAdapter(sweetLogger);
            Logger oldInstance = loggerMap.putIfAbsent(name, newInstance);
            return oldInstance == null ? newInstance : oldInstance;
        }
    }


}
